import { cloneDeep } from "lodash-es";
import type { ElTable } from "element-plus";

interface State {
  loading: boolean;
  total: number;
  pageSize: number;
  page: number;
}

export function useList<T, P = any>(
  request: (params: PageParams & P) => Promise<AxiosResult<PageMo<T>>>,
  getParams?: () => P
) {
  const elTableRef = ref<InstanceType<typeof ElTable>>();
  const list = ref<T[]>([]) as Ref<T[]>;
  const data = ref();
  const state = reactive<State>({
    loading: false,
    total: 0,
    pageSize: 15,
    page: 1
  });
  const getData = async () => {
    try {
      state.loading = true;
      const pageObj: PageParams = {
        Page: state.page,
        PageSize: state.pageSize
      };
      let query: PageParams & P;
      if (getParams) {
        query = Object.assign(pageObj, getParams());
      } else {
        query = Object.assign(pageObj, {} as P);
      }
      console.log(query);
      const res = await request(query);
      state.loading = false;
      if (res?.code == 200) {
        const resData = res.data;
        list.value = cloneDeep(resData.List!);
        state.total = resData.Total || 0;
        list.value = (list.value || []).map((item: T) => {
          return {
            ...item,
            Loading: false,
            Updating: false,
            Deleteing: false,
            Checked: false
          };
        });
        data.value = cloneDeep(res.data);
        await nextTick();
        elTableRef.value?.setScrollTop(0);
      }
    } catch (error) {
      state.loading = false;
      console.log(error);
    }
  };
  const getItem = <T>() => {
    return data.value["Item"] as T;
  };
  const search = () => {
    state.page = 1;
    state.total = 0;
    getData();
  };
  return {
    elTableRef,
    state,
    list,
    getData,
    search,
    getItem
  };
}
